package com.cloudtasks;
import com.cloudtasks.R;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ScanMenuActivity extends Activity {
	
	String UserName = "";
	long UserID;
	long ListID;
	final Context myContext = this;
	private Cursor DBcursor;
	private Database mDb;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_scan_menu);
        
        
        
        // SCAN BUTTON
        Button startScan = (Button)findViewById(R.id.start_scan_button);
        startScan.setOnClickListener(scanButtonListener);  
               
    }
	
	private OnClickListener scanButtonListener = new OnClickListener(){
		public void onClick(View v){						
			// fetch the name of the user				
			try{
				Intent scanIntent = new Intent("com.google.zxing.client.android.SCAN");
				scanIntent.putExtra("SCAN_MODE", "PRODUCT_MODE");
				startActivityForResult(scanIntent, 0);
			}
			catch(Exception e){
				MyTools.displayToastMessage(myContext,e.toString());	
			}
		}
	};
	
    @TargetApi(9)
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
 	   if (requestCode == 0) {
 	      if (resultCode == RESULT_OK) {
 	    	// final String productName;
 	         final String contents = intent.getStringExtra("SCAN_RESULT");
 	         String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
 	       // new Thread(new Runnable() {
 	         //  public void run() {
 	        	   String productName = convertUpcToName(contents);
 	        	   
 	        	  String delimiter =  "[ ]+";
 	              String[] compare = productName.split(delimiter);
 	        if(compare.length == 1 && compare[0].isEmpty())
 	        {
 	        	MyTools.displayToastMessage(this, "No match for UPC code");
 	        }
 	        
 	        else
 	        {
		 	        	// MyTools.displayToastMessage(this, convertUpcToName(contents));
		 	           //}
		 	         //}).start();
		 	         
		 	         //String productName = convertUpcToName(contents);
		 	         MyTools.displayToastMessage(this, productName);
		 	         //Need to search UPC at this point.
		 	         //ResultHandler handler = null;
		 	         //handler.openProductSearch(contents);
		 	        
		 	         // Handle successful scan
		//    		Intent intent2 = new Intent(myContext, AddItemByBrowsingPage2Activity.class);
		//			intent2.putExtras(getIntent().getExtras());
		//			intent2.putExtra("productName", productName);
		//			TabGroupActivity parentActivity = (TabGroupActivity)getParent();
		//			parentActivity.startChildActivity("ScanResultsActivity", intent2);
		 	        
		 	         // Unwrap parameters from last activity: the User's name
		 	        // and also his User ID
		         	Bundle param = getIntent().getExtras(); 
		 	        if(param != null)
		 	        {
		 	        	UserName = param.getString("uname");
		 		        UserID = param.getLong("uid");
		 		    	ListID = param.getLong("lid");
		 	        }
		 	        
		 	        // initialize the Database for this context
			        mDb = new Database(this);
			        mDb.open();	 
		 	         
		 	        ListView lv = (ListView) findViewById(R.id.scan_results_listview);
		 	         DBcursor = mDb.ScanSearchAllItems(productName, ListID );
			        lv.setAdapter(new SimpleCursorAdapter(myContext,  
			        	    R.layout.single_item_searched,
			        	    DBcursor,
			        	    new String[] {Database.KEY_TYPE, Database.KEY_GROC_NAME},
			        	    new int[] { R.id.type_result_textview, R.id.item_result_textview}
			        	));
			        startManagingCursor(DBcursor);
			        TextView changetext = (TextView) findViewById(R.id.scan_results_textview);
					changetext.setText("Found " + DBcursor.getCount() + " matches.");
			        
			        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
						@Override
						public void onItemClick(AdapterView<?> av, View view,
								int pos, long id) {
							String name = ((TextView)view.findViewById(R.id.item_result_textview)).getText().toString();
		
			        		mDb.updateItemCheckedState(id, true);	// mark this item as "checked off"
		
			        		MyTools.displayToastMessage(myContext, "Checked off " + name); 
						}  
			        
			        });
 	        }  //Matches else from above
			 
			
 	      } else if (resultCode == RESULT_CANCELED) {
 	         // Handle cancel
 	      }
 	   }
 	}
 
 // Convert a UPC code (contained in a string) to a product name using a Google API
 public String convertUpcToName(String upcCodeNum) 
 {
 	String key = "\"title\": ";
 	String productName = "";
		String urlBase = "https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyC1rRq2FwiJ3HS4ToOxYhAXEYvxgEW5F6k&country=US&q=";
		String urlText = urlBase + upcCodeNum;
 	//BufferedReader in;
 	String inputLine;
		try {
			
			URL url = new URL(urlText);
			//HttpsURLConnection urlConnection;
		
				HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
		
			   try {
				    //InputStreamReader in_stream = new InputStreamReader(url.openStream()) ;
				   	//in = new BufferedReader(new InputStreamReader(url.openStream()));
				   	//InputStream in_stream = new BufferedInputStream(urlConnection.getInputStream());
				   	//InputStreamReader in_reader = new InputStreamReader(in_stream);
				   	//in = new BufferedReader(in_reader);
				   	
				   	BufferedReader in = new BufferedReader(
		                    new InputStreamReader(
		                    urlConnection.getInputStream()));
				   	//readStream(in_stream);
				  // Read the query from Google's Search API for Shopping line-by-line
					while ((inputLine = in.readLine()) != null) 
					{
						// Stop reading when key is found; extract the product name
						int keyIndex = inputLine.indexOf(key);
						if (keyIndex != -1) 
						{
							productName = inputLine.substring(keyIndex + key.length());
							int startIndex = productName.indexOf("\"");
							int endIndex = productName.lastIndexOf("\"");
							productName = productName.substring(startIndex + 1, endIndex);
							break;
						}
					}
					
					urlConnection.disconnect();
			   }catch (IOException e) {
					// Auto-generated catch block
					// TODO Fill this in
				   MyTools.displayToastMessage(myContext,"Caught IO Exception");	
				
				} 
			   
		}catch (MalformedURLException e) {
			// Auto-generated catch block
			// TODO Fill this in
		} 
		catch (IOException e) {
			// Auto-generated catch block
			// TODO Fill this in
		   MyTools.displayToastMessage(myContext,"Caught IO Exception");	
		
		} 
		
			 return productName;
	}
			   
				     
				     
			   
			 
			
			
			
			
	/*		
			
			//URL url = new URL(urlText);
			
			//String inputLine;

			// Read the query from Google's Search API for Shopping line-by-line
			while ((inputLine = in.readLine()) != null) {
				// Stop reading when key is found; extract the product name
				int keyIndex = inputLine.indexOf(key);
				if (keyIndex != -1) {
					productName = inputLine.substring(keyIndex + key.length());
					//int startIndex = productName.indexOf("\"");
					//int endIndex = productName.lastIndexOf("\"");
					//productName = productName.substring(startIndex + 1, endIndex);
					break;
				}
			in.close();
			}
		} catch (MalformedURLException e) {
			// Auto-generated catch block
			// TODO Fill this in
		} catch (IOException e) {
			// Auto-generated catch block
			// TODO Fill this in
		}
		return productName;
	}
	*/
	@Override
    public void onBackPressed() {
    // do something on back.
    	finish();
    return;
    }
}